import dayjs from 'dayjs'

// 处理数据
export const handleDataProcessing = (taskList, milestoneList, projectNode) => {
  // 处理 taskList
  const processedTopIssueTask = taskList.topIssueTask.map(issue => {
    const processedTasks = {}

    if (issue.tasks && typeof issue.tasks === 'object') {
      Object.entries(issue.tasks).forEach(([rowKey, taskList]) => {
        if (Array.isArray(taskList)) {
          const formattedTasks = taskList.reduce((acc, task, index) => {
            acc[`task_${index}`] = {
              ...task,
              lineType: false,
              startTime: dayjs(task.estimatedStartTime).format('YYYY-MM-DD'),
              endTime: dayjs(task.estimatedEndTime).format('YYYY-MM-DD')
            }

            return acc
          }, {})

          processedTasks[rowKey] = formattedTasks;
        } else {
          console.warn(`tasks["${rowKey}"] is not an array.`);
        }
      })
    }

    return {
      ...issue,
      tasks: processedTasks
    }
  })

  // 处理 milestoneList
  const processedMilestoneList = milestoneList.reduce((acc, milestone, index) => {
    acc[`task_${index}`] = {
      configId: milestone.configId,
      projectId: milestone.projectId,
      configName: milestone.configName,
      lineType: false,
      startTime: dayjs(milestone.startTime).format('YYYY-MM-DD'),
      endTime: dayjs(milestone.endTime).format('YYYY-MM-DD'),
      progress: milestone.progress,
      configStatus: milestone.configStatus
    }

    return acc
  }, {})

  // 最终返回的对象
  return {
    startTime: taskList.startTime,
    endTime: taskList.endTime,
    milestoneList: [processedMilestoneList],
    projectNodeList: projectNode,
    taskList: processedTopIssueTask
  }
}

// 根据整个项目的开始时间和结束时间生成中间的时间轴数据
export const generateFormattedData = (startTime, endTime) => {
  // 确保 startTime 和 endTime 是有效的日期格式
  const startDate = dayjs(startTime)
  const endDate = dayjs(endTime)

  if (!startDate.isValid() || !endDate.isValid()) {
      console.error("Invalid start or end time in ganttData");
      return []
  }

  let formattedData = []

  // 初始化当前月份为 startTime
  let currentDate = startDate.clone()

  // 按月迭代，直到当前月份超过 endTime
  while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'month')) {
      // 收集月份信息，格式化为 "MM月"
      formattedData.push({
          key: `${currentDate.format('YYYY')}-${currentDate.format('MM')}`,
          year: currentDate.format('YYYY'), // 年份
          month: currentDate.format('MM') + '月'  // 月份
      });

      // 增加一个月
      currentDate = currentDate.add(1, 'month')
  }

  return formattedData
}


export const getNodesInMonth = (monthItem, projectItem) => {
  if (!projectItem || !Array.isArray(projectItem)) {
    return []
  }

  const monthKey = monthItem.key

  return projectItem.filter(node => {
    return dayjs(node.nodeTime).format('YYYY-MM') === monthKey
  })
}


// 动态计算当前月的天数，设置移动距离
export const positionNode = (node, labelWidth) => {  
  const daysInMonth = dayjs(node.nodeTime).daysInMonth() // 动态计算当前月的天数
  const num = labelWidth / daysInMonth 
  
  return ((dayjs(node.nodeTime).date() * num) - (labelWidth / 2)) +  'px'
}

// 辅助函数：检查是否是有效的数字
const isValidNumber = (value) => {
  return value !== undefined && value !== null && !isNaN(Number(value))
}

// 根据状态设置颜色
export const getBoxStyle = (row) => {
  // 确保 configStatus 和 issuestatus 是有效的数字类型
  const configStatus = isValidNumber(row.configStatus)
      ? Number(row.configStatus)
      : undefined

  const issuestatus = isValidNumber(row.issuestatus)
      ? Number(row.issuestatus)
      : undefined

  // 初始化样式对象
  let styleObj = { bgColor: '', textColor: '' }
  // 分别根据 configStatus 和 issuestatus 设置样式
  if (configStatus !== undefined && configStatus !== null) {
    switch (configStatus) {
      case 0:
        styleObj.bgColor = 'linear-gradient(90deg, #BCBCBC 0%, #868686 100%)'
        styleObj.textColor = '#FFF'
        break;
      case 1:
        if(dayjs().isAfter(dayjs(row.endTime))){
          styleObj.bgColor = 'linear-gradient(90deg, #FFB120 0%, #D74510 100%)'
          styleObj.textColor = '#FFFFFF'
        }else{
          styleObj.bgColor = 'linear-gradient(90deg, #15B9BA 0%, #0487B2 100%)'
          styleObj.textColor = '#FFFFFF'
        }
        break;
      case 2:
        styleObj.bgColor = 'linear-gradient(90deg, #26D181 0%, #079F56 100%)'
        styleObj.textColor = '#FFFFFF'
        break;
      case 3:
        styleObj.bgColor = 'linear-gradient(90deg, #FFB120 0%, #D74510 100%)'
        styleObj.textColor = '#FFFFFF'
        break;
      default:
        styleObj.bgColor = 'linear-gradient(90deg, #FFB120 0%, #D74510 100%)'
        styleObj.textColor = 'black'
        break;
    }
  } else {
    styleObj.bgColor = '#409EFF'
    styleObj.textColor = '#FFFFFF'
  }

  if (issuestatus !== undefined && issuestatus !== null) {
    switch (issuestatus) {
      case 1:
        styleObj.bgColor = 'rgba(175, 183, 189, 0.80)'
        styleObj.textColor = '#555'
        break;
      case 2:
        styleObj.bgColor = 'rgba(56, 99, 255, 0.66)'
        styleObj.textColor = '#FFF'
        break;
      case 3:
        styleObj.bgColor = 'rgba(36, 200, 131, 0.56)'
        styleObj.textColor = '#414141'
        break;
      case 4:
        styleObj.bgColor = 'rgba(255, 96, 95, 0.80)'
        styleObj.textColor = '#FFF'
        break;
      default:
        break;
    }
  }

  return styleObj;
}